import hashlib

from hypium import *
from hypium.model import *


OPTION_FLAG = [
    "clickable",  # 单击
    "longClickable",  # 长按
    "scrollable"  # 滚动
]

BASE_OPTION = [
    "back",
    "home"
]

class Widget():
    """
    UTG中的Edge
    """
    def __init__(self, option, attributes = None):

        if option not in BASE_OPTION:
            self.attributes = attributes
        self.option = option

    def build_edge(self, source, target):
        self.source_status = source
        self.target_status = target

    def do(self, device):
        device.logger.info(f"do widget - option: {self.option}")
        if self.attributes:
            device.logger.info(f"do widget - attributes: {self.attributes}")
        if self.option == OPTION_FLAG[0]:
            self.click(device.driver)
        elif self.option == OPTION_FLAG[1]:
            self.long_click(device.driver)
        elif self.option == OPTION_FLAG[2]:
            self.swipe(device.driver)
        elif self.option == BASE_OPTION[0]:
            self.back(device.driver)
        elif self.option == BASE_OPTION[1]:
            self.home(device.driver)

    def click(self, driver):
        bounds = self.attributes["bounds"]
        coords_list = bounds.replace("[", "").replace("]", ",").split(",")[:4]
        x1, y1, x2, y2 = map(int, coords_list)
        driver.touch(((x1 + x2) / 2, (y1 + y2) / 2))


    def long_click(self, driver):
        bounds = self.attributes["bounds"]
        coords_list = bounds.replace("[", "").replace("]", ",").split(",")[:4]
        x1, y1, x2, y2 = map(int, coords_list)
        driver.touch(((x1 + x2) / 2, (y1 + y2) / 2), mode="long")

    def swipe(self, driver):
        driver.swipe(UiParam.UP, area=BY.id(self.attributes["id"]).scrollable("true").type(self.attributes["type"]))

    def back(self, driver):
        driver.swipe_to_back()

    def home(self, driver):
        driver.swipe_to_home()

class PageStatus:
    """
    UTG中的NODE
    """
    def __init__(self, device):
        self.device = device
        # 控件相关
        self.widget_tree_data = self.device.get_widget_tree_json()
        self.widget_id_tree = self.get_widget_id_tree(self.widget_tree_data)
        self.state_id = hashlib.md5(str(self.widget_id_tree).encode('utf - 8')).hexdigest()
        # 可操作控件
        self.op_widgets = []
        self.get_opable_widgets(self.widget_tree_data)
        # 截图获取,名称为id
        mame = f"{self.state_id}.png"
        self.screencap_dir = self.device.get_screencap(mame)
        # 本页面已执行的操作(相邻的边)
        self.adjacent_event = []

    def __eq__(self, other):
        return self.state_id == other.state_id

    def get_opable_widgets(self, widget_tree_data):
        if "attributes" in widget_tree_data:
            attributes = widget_tree_data["attributes"]
            for op in OPTION_FLAG:
                if op in attributes.keys():
                    if attributes[op] == "true":
                        self.op_widgets.append(Widget(op, attributes))
                        break
        if "children" in widget_tree_data:
            for widget in widget_tree_data["children"]:
                self.get_opable_widgets(widget)

    def add_event(self, widget):
        self.adjacent_event.append(widget)

    def get_widget_id_tree(self, widget_tree_json):
        result = {}
        if "children" in widget_tree_json:
            for child in widget_tree_json["children"]:
                if "attributes" in child and "accessibilityId" in child["attributes"]:
                    child_id = child["attributes"]["accessibilityId"]
                    sub_dict = self.get_widget_id_tree(child)
                    result[child_id] = sub_dict
        return result
